<template>
    <el-row class="login-page">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="6" :offset="3" class="form">
            <!-- 注册表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item prop = "customer_name">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.customer_name"></el-input>
                </el-form-item>
                <el-form-item prop = "password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item prop = "repassword">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.repassword"></el-input>
                </el-form-item>
                <el-form-item label="请选择你的身份">
                    <el-radio-group v-model="registerData.registerType">
                        <el-radio value="顾客">顾客</el-radio>
                        <el-radio value="商家">商家</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="register()">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterData()">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-else :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>登录</h1>
                </el-form-item>
                <el-form-item prop="customer_name">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.customer_name"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item label="请选择你的身份">
                    <el-radio-group v-model="registerData.registerType">
                        <el-radio value="顾客">顾客</el-radio>
                        <el-radio value="商家">商家</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<script lang = "ts" setup>

import { ref } from "vue"
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useTokenStore } from '@/store/token';
import { useCustomerInfoStore } from '@/store/customerInfo';
import { useBusinessInfoStore } from '@/store/businessInfo';
import { customerInfoService } from '@/api/Customer';
import { businessInfoService } from '@/api/Business';
import { useLoginStore } from '@/store/login'
//导入与后端登录/注册有关的函数
import {customerRegisterService, customerLoginService, businessLoginService, businessRegisterService} from '@/api/login'

//判断是否为注册页面
const isRegister = ref(false)

const router = useRouter();

const tokenStore = useTokenStore();

const customerInfoStore = useCustomerInfoStore();

const businessInfoStore = useBusinessInfoStore();

const loginStore = useLoginStore();

//定义注册的数据
const registerData = ref({
    customer_name: '',
    business_name: '',
    password: '',
    repassword: '',
    registerType: '顾客',
})

//定义二次输入密码的rule
const checkRePassword = (rule: any, value: any, callback: any) => {
    if(value === '') {
        callback(new Error('请再次输入密码'))
    }else if(value !== registerData.value.password) {
        callback(new Error('请确保两次输入的密码一样'))
    }else {
        callback()
    }
}

//定义rule
const rules = {
    customer_name: [
        {required: true, message: '请输入用户名', trigger: 'blur'},
        {min: 2, max: 10, message: '用户名长度要在2-10之间', trigger: 'blur'},
    ],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 6, max: 20, message: '密码长度要在6-20之间', trigger: 'blur'},
    ],
    repassword: [
        { validator: checkRePassword, trigger:'blur'}
    ]
}

//点击注册按钮后提交数据到后端
const register = async() => {
    if(registerData.value.registerType == '顾客') {
        let result = await customerRegisterService(registerData.value);
        ElMessage.success(result.message ? result.message : '注册成功');
        if(result.message) {
            isRegister.value = false;
            clearRegisterData();
        }
    }else {
        registerData.value.business_name = registerData.value.customer_name;
        let result = await businessRegisterService(registerData.value);
        ElMessage.success(result.message ? result.message : '注册成功');
        if(result.message) {
            isRegister.value = false;
            clearRegisterData();
        }
    }
}

//登录界面的数据，复用注册界面的数据模型
//登录表单数据校验，同样复用注册界面的
//登录函数
const login =async () => {
    //调用接口，完成登录
    if(registerData.value.registerType == '顾客') {
        let result = await customerLoginService(registerData.value);
        ElMessage.success(result.message ? result.message : '登录成功');
        tokenStore.setToken(result.data);
        const customerInfoResult = await customerInfoService();
        const customerInfo = customerInfoResult.data;
        customerInfoStore.setCustomerInfo(customerInfo);
        loginStore.setLoginInfo(1);
        if(result.message) {
            clearRegisterData();
            router.push({ path: '/'});
        }
    }else {
        registerData.value.business_name = registerData.value.customer_name;
        let result = await businessLoginService(registerData.value);
        ElMessage.success(result.message ? result.message : '登录成功');
        tokenStore.setToken(result.data);
        const businessInfoResult = await businessInfoService();
        const businessInfo = businessInfoResult.data;
        businessInfoStore.setBusinessInfo(businessInfo);
        loginStore.setLoginInfo(2);
        if(result.message) {
            clearRegisterData();
            router.push('/');
        }
    }
}

//定义函数，清空数据模型的数据
const clearRegisterData = () => {
    registerData.value = {
        customer_name: '',
        business_name: '',
        password: '',
        repassword: '',
        registerType: '顾客',
    }
}
</script>

<style scoped>

  .login-page {
    height: 100vh;
    background-color: #fff;
  }

  /* 控制登录/注册左边的图片样式 */
  .bg {
      background: url('@/assets/login_bg.png') no-repeat center / cover;
      border-radius: 0 20px 20px 0;
  }

  .form {
      display: flex;
      flex-direction: column;
      justify-content: center;
      user-select: none;
  }

  .title {
      margin: 0 auto;
  }

  .button {
      width: 100%;
  }

  .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
  }
</style>